package com.tz.farmer.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.model.EnrollInfo;
import com.tz.farmer.service.ActivityService;
import com.tz.farmer.so.BaseSo;
import com.tz.farmer.util.Configure;
import com.tz.farmer.util.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @description: 食安活动报名（h5）
 * @name BusinessController
 * @author: xhj
 * @date: 2021/7/13
 * @version V1.0
 */
@RestController
@RequestMapping("activity")
@Api(value = "食安活动报名（h5）", tags = "食安活动报名（h5）控制器")
public class ActivityController {

    private static Logger logger = LoggerFactory.getLogger(ActivityController.class);

    @Resource
    ActivityService activityService;
    @Resource
    JdbcTemplate jdbcTemplate;

    /**
     * @description: 食安活动报名
     * @name pushBussinessInfo
     * @author: xhj
     * @date: 2021/7/13 11:35
     * @version V1.0
     */
    @ApiOperation("食安活动报名")
    @PostMapping("enroll")
    @ApiImplicitParams({
    })
    public ResultEx enroll(@RequestBody EnrollInfo enrollInfo) {
        try {
            enrollInfo.setApplyTime(LocalDateTime.now());
            activityService.save(enrollInfo);
        } catch (Exception e) {
            logger.error("报名失败", e);
            return ResultEx.builder().makeFailedResult("报名失败");

        }
        return ResultEx.builder().makeSuccessResult("报名成功");

    }


    /**
     * 微信登录app获取openId
     *
     * @return
     */
    @GetMapping("/appLogin")
    @ApiOperation("微信接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "", defaultValue = ""),
    }
    )
    public ResultEx appLogin(@Param("code") String code) {
        logger.info("前端传入code值===============" + code);
        String result = "";
        try {
            result = HttpUtils.doGet(
                    "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                            + Configure.mini_appID + "&secret="
                            + Configure.mini_secret + "&code="
                            + code
                            + "&grant_type=authorization_code", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObj = JSONObject.parseObject(result);//解析从微信服务器上获取到的json字符串
        logger.info("jsonObj===============" + jsonObj);

        String openId = jsonObj.get("openid") + "";
        logger.info("返回openId值===============" + openId);
        return ResultEx.builder().makeSuccessResult(openId);
    }

    /**
     * @description: 查询食安活动信息
     * @name businessInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("查询食安活动信息")
    @GetMapping("activityInfos")
    public ResultEx getActivityInfos(BaseSo baseSo) {
        try {
            return activityService.getActivityInfos(baseSo);
        } catch (Exception e) {
            logger.error("食安活动信息获取失败", e);
            return ResultEx.builder().makeFailedResult("食安活动信息获取失败");

        }
    }


    /**
     * 本地图片转换成base64字符串
     *
     * @param imgFile 图片本地路径
     * @return
     */
    @GetMapping("photo")
    public  void ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
//        InputStream in = null;
//        byte[] data = null;
//        // 读取图片字节数组
//        try {
//            in = new FileInputStream(imgFile);
//            data = new byte[in.available()];
//            in.read(data);
//            in.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
//        String sql="update add_link set zx='data:image/.jpg;base64,"+encoder.encode(data)+"'";
        String sql="INSERT INTO test VALUES(3, 'titanic', LOAD_FILE('Users/xuhongjun/Documents/1638770422771050.mp4'))";

        jdbcTemplate.execute(sql);


    }
}
